﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ZWZ.Web.Codes
{
    public class RequestModule : IHttpModule
    {
        public void Dispose()
        {

        }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }
        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            var ctx = HttpContext.Current;
            string installurl = Config.ConfigAdapter.SiteDataMgr.Groups["InitSetting"].Settings["PageUrl"].Value;

            //验证是否是访问页面
            if (ctx.Request.CurrentExecutionFilePathExtension != ".aspx") { return; }

            //验证软件是否安装
            if (!ctx.Request.RawUrl.ToLower().StartsWith(installurl.ToLower()) &&
                Config.ConfigAdapter.SiteDataMgr.Groups["InitSetting"].Settings["HasInited"].Value != true.ToString())
            {
                ctx.Response.Redirect(installurl);
                return;
            }

            //如果用户没有登录
            if (Codes.LoginHelper.CurrentUser == null)
            {

                bool forbit = false;
                foreach (var dir in Config.ConfigAdapter.SiteDataMgr.Groups["Req_PageDir"].Settings)
                {
                    if (ctx.Request.RawUrl.ToLower().StartsWith(dir.Value.ToLower())) { forbit = true; break; }
                }
                foreach (var file in Config.ConfigAdapter.SiteDataMgr.Groups["Req_PageFile"].Settings)
                {
                    if (ctx.Request.RawUrl.ToLower().StartsWith(file.Value.ToLower())) { forbit = false; break; }
                }
                //如果禁止访问跳转到登录页面
                if (forbit)
                {
                    ctx.Response.Redirect(string.Format("{0}?url={1}",
                        Config.ConfigAdapter.SiteDataMgr.Groups["Req_PageFile"].Settings["PageLogin"].Value,
                        ctx.Server.UrlEncode(ctx.Request.RawUrl)));
                }
            }
        }
        void context_BeginRequest(object sender, EventArgs e)
        {
        }
    }
}